package com.wyw.leetcode.learning.medium;

import com.wyw.leetcode.simple.parent.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @Title       leetcode topic 142
 * @Description 二叉树的层序遍历
 *      给你二叉树的根节点 root ，返回其节点值的 层序遍历 。 （即逐层地，从左到右访问所有节点）。
 * @Author Mr Wu yewen.wu.china@gmail.com
 * @Date 2023/3/8 16:30
 * Update History:
 * Author        Time            Content
 */
public class Topic102 {

    public static void main(String[] args) {
        TreeNode node = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        TreeNode node4 = new TreeNode(4);
        TreeNode node5 = new TreeNode(5);
        TreeNode node6 = new TreeNode(6);
        TreeNode node7 = new TreeNode(7);
        TreeNode node8 = new TreeNode(8);
        TreeNode node9 = new TreeNode(9);
        TreeNode node10 = new TreeNode(10);

        node.left = node2;
        node2.left = node4;
        node4.right = node8;
        node2.right = node5;
        node10.right = node3;
        node3.left = node6;
        node5.right = node9;
        node3.right = node7;
        node7.left = node10;

        List<List<Integer>> lists = levelOrder(node);
        System.out.println("end");
    }

    /**
     * 广度优先
     * @param root
     * @return
     */
    public static List<List<Integer>> levelOrder(TreeNode root) {

        List<List<Integer>> ret = new ArrayList<>();
        if (root == null) {
            return ret;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            List<Integer> level = new ArrayList<>();
            int currentLevelSize = queue.size();
            for (int i = 1; i <= currentLevelSize; ++i) {
                TreeNode node = queue.poll();
                level.add(node.val);
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            ret.add(level);
        }

        return ret;

    }


}
